from django.test import TestCase
from django.test.client import Client 
from models import Poem 
import unittest

class AddPoemIntegrationTest(TestCase):
  fixtures = ['poems.json', 'poems']

  def setUp(self):
    self.client = Client()
    
  def test_add_poem_fails_with_empty_input(self): 
    response = self.client.post('/baudlr/add_poem/', {})
    self.assertEquals(200, response.status_code)
    self.assert_stays_on_add_poem_page(response)
  
  def test_add_poem_redirects_to_list_poems_page_after_successful_post(self):
    response = self.post_test_data()
    self.assertEquals(302, response.status_code)
    self.assert_redirects_to_url('/baudlr/list_poems', response)   

  def test_new_poem_is_displayed_in_poem_list(self):
    self.post_test_data()
    response = self.client.get('/baudlr/list_poems/', {})

  def post_test_data(self):
    return self.client.post('/baudlr/add_poem/', {'author' : 'Charles Baudelaire',
                                                  'title' : 'Les Fleurs du mal',
                                                  'year_of_publication' : '1857',
                                                  'text' :
                                                  """
                                                  If rape and poison, dagger and burning,
                                                  Have still not embroidered their pleasant designs
                                                  On the banal canvas of our pitiable destinies,
                                                  It's because our souls, alas, are not bold enough!
                                                  """})

  def assert_stays_on_add_poem_page(self, response):
    return self.assertEquals('add_poem.html', response.template[0].name)
  
  def assert_redirects_to_url(self, expected_url, response):
    return self.assertEquals(expected_url, response.headers['Location'])

class ListPoemsIntegrationTest(TestCase):
  fixtures = ['poems.json', 'poems']

  def setUp(self):
    self.client = Client()

  def test_lists_all_existing_poems(self):
    response = self.client.get('/baudlr/list_poems/', {})
    self.assertEquals(200, response.status_code)
    self.assertTrue(str(response).find("My mother groan'd!") != -1)